import dayjs from "dayjs";
//import roleForm from "../form/role.vue";
//import editForm from "../form/index.vue";
//import editField from "../form/editField.vue";
//import { zxcvbn } from "@zxcvbn-ts/core";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
//import croppingUpload from "../upload.vue";
//import { usePublicHooks } from "@/views/metaTable/hooks";

//import { addDialog } from "@/components/ReDialog";
import { type PaginationProps } from "@pureadmin/table";

import { getKeyList } from "@pureadmin/utils";
import {
  //getRoleIds,
  getTableClassList,
  getTableInfoList,
  //saveForm,
  delFormByIDS
  //generateForm
  //getAllRoleList
} from "@/api/metaTable";

import {
  type Ref,
  //h,
  ref,
  toRaw,
  // watch,
  computed,
  reactive,
  onMounted
} from "vue";

export function useUser(tableRef: Ref, treeRef: Ref) {
  //const formRef = ref();
  //const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  //const avatarInfo = ref();
  //const switchLoadMap = ref({});
  //const { switchStyle } = usePublicHooks();
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const selRow = ref();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const form = reactive({
    // 左侧部门树的id
    deptId: 0,
    tableName: "",
    status: "",
    onePage: pagination,
    sortName: "id",
    sort: false
  });
  const columns: TableColumnList = [
    {
      label: "编号",
      prop: "id",
      width: 90,
      sortable: "custom"
    },
    {
      label: "源表名称",
      prop: "tableName",
      minWidth: 130,
      sortable: "custom"
    },
    {
      label: "是否生成",
      prop: "tableIsFaBu",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.tableIsFaBu === 0 ? "danger" : ""}
          effect="plain"
        >
          {row.tableIsFaBu === 0 ? "未生成" : "已生成"}
        </el-tag>
      )
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.status === 0 ? "danger" : ""}
          effect="plain"
        >
          {row.status === 0 ? "已停用" : "已启用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "addTime",
      formatter: ({ addTime }) => dayjs(addTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 100,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  //修改设置
  function handleUpdate(row) {
    console.log("row-selTable: " + row);
  }

  //远程排序
  function sortChange({ column }) {
    form.sort = column.order == "ascending" ? true : false;
    form.sortName = column.property;
    onSearch();
  }

  function handleDelete(row) {
    message(`您删除了用户编号为${row.id}的这条数据`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  //分页选择
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
    console.log("handleCurrentChange 11111");
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  async function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    const frmIDS = getKeyList(curSelected, "id");

    tableRef.value.getTableRef().clearSelection();
    const Result = await delFormByIDS({ ids: frmIDS });
    if (Result.isSuccess) {
      message(`已删除用户编号为 ${frmIDS} 的数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message(Result.msg, { type: "error" });
    }
  }

  async function onSearch() {
    loading.value = true;
    const Result = await getTableInfoList(toRaw(form));

    if (Result.isSuccess) {
      dataList.value = Result.result;
      pagination.total = Result.onePage.total;
      pagination.pageSize = Result.onePage.pageSize;
      pagination.currentPage = Result.onePage.currentPage;
    } else {
      message(Result.msg, { type: "error" });
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.deptId = 0;
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ id, selected }) {
    form.deptId = selected ? id : "";
    onSearch();
  }

  /*
  function formatHigherDeptOptions(treeList) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }
*/
  //根据JSON表单生成数据库实体
  async function generateFormToTable(row) {
    //const Result = await generateForm({ id: row.id });
    selRow.value = row;

    message("操作成功！", { type: "success" });
  }

  onMounted(async () => {
    treeLoading.value = true;

    // 归属部门
    const Result = await getTableClassList({ classType: 1 });
    const currentRS = Result.result;
    higherDeptOptions.value = handleTree(
      currentRS,
      currentRS["id"],
      currentRS["parentID"],
      currentRS["id"]
    );
    treeData.value = handleTree(
      currentRS,
      currentRS["id"],
      currentRS["parentID"],
      currentRS["id"]
    );
    treeLoading.value = false;
    await onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    onbatchDel,
    //openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    sortChange,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    //openEditFieldDialog,
    generateFormToTable
  };
}
